import 'dart:convert';

import '../models/index.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'package:dio/dio.dart';

class Global {
  static SharedPreferences _prefs;
  static Profile profile = Profile();
  static bool isReFetchWhenReseveMessage = true;
  static String currentChatUserId;

  static String imServerHost = "chat.digintech.cn";
  static int imServerPort = 80;

  static String appServerHost = "chat.digintech.cn";
  static int appServerPort = 8888;

  static Future<void> initFlutterWildfire() async {
    await FlutterWildfire.init(imServerHost, imServerPort);
    FlutterWildfire.on("connectionStatusChange", connectionStatusChangeHandler);
    FlutterWildfire.on("receiveMessage", (messages) {
      print('global receiveMessage');
      // print(messages);
    });
  }

  static connectionStatusChangeHandler(status) {
    /**
       *  int ConnectionStatusRejected = -3;
          int ConnectionStatusLogout = -2;
          int ConnectionStatusUnconnected = -1;
          int ConnectionStatusConnecting = 0;
          int ConnectionStatusConnected = 1;
          int ConnectionStatusReceiveing = 2;
       */
    print('global status =  $status' );
  }

  // 是否为release版
  static bool get isRelease => bool.fromEnvironment("dart.vm.product");

  //初始化全局信息，会在APP启动时执行
  static Future init() async {
    await initFlutterWildfire();
    _prefs = await SharedPreferences.getInstance();
    var _profile = _prefs.getString("profile");
    if (_profile != null) {
      try {
        profile = Profile.fromJson(jsonDecode(_profile));
        if (profile?.user != null &&
            profile.token != null &&
            profile.token.length > 0) {
          print('profile = ' + profile.toString());
          FlutterWildfire.connect(profile.user.uid, profile.token);
        } else {
          print('还没有登录');
        }
      } catch (e) {
        print('FlutterWildfire init error');
        // print(e);
      }
    }
  }

  static login(String mobile, String code) async {
    String clientId;
    Response response;
    Dio dio = new Dio();
    try {
      clientId = await FlutterWildfire.getClientId();
      String _loginUrl = 'https://$appServerHost:$appServerPort/login';
      response = await dio.post(_loginUrl,
          data: {"clientId": clientId, "mobile": mobile, 'code': code});
      if (response.data['code'] != 0) {
        throw response.data['message'];
      }
      LoginResult result = LoginResult.fromJson(response.data['result']);
      String userId = result.userId;
      String token = result.token;
      profile.token = token;
      profile.lastLogin = mobile;
      await FlutterWildfire.connect(userId, token);
      return true;
    } catch (e) {
      print('global login error');
      print(e);
      return false;
    } finally {
      // clientId = 'Failed to get client id.';
      // client.close();
    }
  }

  // 持久化Profile信息
  static saveProfile() {
    print(profile);
    _prefs.setString("profile", jsonEncode(profile.toJson()));
  }
}
